from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import FileUtil, MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 固定配置 ==========
HOSPITAL_CODE = 'H001'
HOSPITAL_NAME = '西安肿瘤医院'
CANCERS = ['肺癌', '胃癌', '乳腺癌', '肝癌', '结直肠癌']
VISIT_TYPES = ['门诊', '住院']

# 固定的患者类型与对应生成数量
PATIENT_TYPE_CONFIG = {
    '01': ('初诊患者', 100),
    '02': ('复诊患者', 80),
    '03': ('疑似患者', 50),
    '04': ('确诊患者', 120)
}


# ========== 核心生成函数 ==========
def generate_pv_records_by_patient_type():
    sql_statements = []
    patient_id_counter = 1001
    visit_sn_counter = 2001

    for cancer in CANCERS:
        for code, (ptype, count) in PATIENT_TYPE_CONFIG.items():
            for _ in range(count):
                patient_id = f"PT{patient_id_counter}"
                visit_sn = f"VIS{visit_sn_counter}"
                patient_id_counter += 1
                visit_sn_counter += 1

                visit_type = random.choice(VISIT_TYPES)
                visit_times = 1 if code == '01' else random.randint(2, 6)
                visit_datetime = fake.date_time_between(
                    start_date='2025-07-01', end_date='2025-07-31'
                ).strftime('%Y-%m-%d %H:%M:%S')

                data = {
                    'patient_id': patient_id,
                    'visit_sn': visit_sn,
                    'hospital_code': HOSPITAL_CODE,
                    'hospital_name': HOSPITAL_NAME,
                    'cancer': cancer,
                    'visit_type': visit_type,
                    'visit_times': visit_times,
                    'patient_type_code': code,
                    'patient_type': ptype,
                    'visit_datetime': visit_datetime,
                    'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }

                sql = _generate_sql('b02_1', data)
                sql_statements.append(sql)

    return sql_statements


# ========== SQL 生成函数 ==========
def _generate_sql(table, data):
    columns = ', '.join([f'`{k}`' for k in data.keys()])
    values = []
    for v in data.values():
        if v is None:
            values.append('NULL')
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({columns}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    records = generate_pv_records_by_patient_type()
    print(records)
    # 写入数据库
    # MysqlUtils_AI.insert_data_to_hub(records, 'b02_1')
    # 或写入 SQL 文件
    # FileUtil.generate_sql_file(records, "b02_1_pv_by_type.sql")
